
const path = require('path');
const Koa = require('koa');
const app = new Koa();

const cors = require('koa2-cors');
const bodyParser = require('koa-bodyparser');
const Router = require('koa-router');

let router = new Router();

const logDir = path.join(__dirname,'logs');
const log4js = require('log4js');
log4js.configure({
    appenders: {
        out: {
            type: 'stdout'
        },
        access: {
            type: 'dateFile',
            filename: path.join(logDir,'access.log'),
            alwaysIncludePattern:true,
            compress:true,
            keepFileExt:true,
        },
        errs:{
            type:'file',
            filename:path.join(logDir,'errs.log'),
            compress:true,
            maxLogSize:5 * 1024 * 1024, // 5M
            backups:5,
        }
    },
    categories: {
        access: {
            appenders: ['access'],
            level: 'info'
        },
        default: {
            appenders: ['out'],
            level:'debug'
        },
        errs:{
            appenders:['errs'],
            level:'error'
        }
    }
});
const accessLogger = log4js.getLogger('access');
const defaultLogger = log4js.getLogger();
const errLogger = log4js.getLogger('errs');

///-------------
// middlewares
const logger = function(){
    return async (ctx,next)=>{
        accessLogger.info('doing url:' + ctx.request.url);
        let start = Date.now();
        await next();
        let spendTime = Date.now() - start;
        accessLogger.info(`process url:${ctx.request.url} spendTime:${spendTime}ms`);
    }
};

const errors = function(){
    return async (ctx,next)=>{
        try {
            await next();
        }catch (e) {
            errLogger.error(e.message);
            ctx.body = {
                err:1,
                msg:e.message
            }
        }
    }
};

///------------
router.get('/',async (ctx)=>{
   ctx.body = {
       msg:'home'
   }
});

router.get('/login',async (ctx)=>{
    ctx.body = {
        msg:'login'
    }
});

router.get('/delay',async ctx=>{
    await async_delay(3000);
    ctx.body = {
        msg:'delay 3000ms'
    };
});

router.get('/error',async ctx=>{
    throw new Error('can not found error page!');
});

function async_delay(ms){
    return new Promise(resolve => {
        setTimeout(()=>{
            resolve();
        },ms);
    })
}


app.use(errors());
app.use(logger());
app.use(cors());
app.use(bodyParser());
app.use(router.routes()).use(router.allowedMethods());


app.listen(3000,()=>{
    defaultLogger.info('start http://localhost:3000');
});
